package me.luraframework.auth.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.google.common.collect.ImmutableMap;
import me.luraframework.auth.exception.InvalidTokenException;
import me.luraframework.auth.security.dto.JwtUserDto;
import me.luraframework.commons.auth.UserContext;
import me.luraframework.core.commons.JsonUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

@Component
public class TokenProvider {

    private static final String USER_CLAIM_KEY = "USER";
    private static final String USER_TYPE_CLAIM_KEY = "TYPE";


    public String createToken(UserContext user) {
        return JWT.create()
                  // .withClaim(USER_TYPE_CLAIM_KEY, user.getUserType().name())
                  .withClaim(USER_CLAIM_KEY, JsonUtils.toStr(user))
                  .sign(Algorithm.HMAC256(user.getUsername()));

    }

    public JwtUserDto checkToken(String token) {
        try {
            String userStr = JWT.decode(token).getClaim(USER_CLAIM_KEY).asString();
            JwtUserDto jwtUser;
            // if (JwtUser.UserType.valueOf(userType) == JwtUser.UserType.CUSTOMER) {
                jwtUser = JsonUtils.toObj(userStr, JwtUserDto.class);
            // }else if(JwtUser.UserType.valueOf(userType) == JwtUser.UserType.BUSINESS){
            //     jwtUser = JsonUtils.toObj(userStr, BusinessJwtUser.class);
            // }else {
            //     throw new InvalidTokenException(ImmutableMap.of("token", token));
            // }
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(jwtUser.getUsername())).build();
            jwtVerifier.verify(token);
            return jwtUser;
        } catch (Exception e) {
            throw new InvalidTokenException(ImmutableMap.of("token", token));
        }
    }

    public String getToken(HttpServletRequest request) {
        return request.getHeader(HttpHeaders.AUTHORIZATION);
    }




}
